import store from '@/store'
import { set } from 'nprogress';

function checkPermission(el, binding) {
  const { value } = binding
  const roles = store.getters && store.getters.roles
  const permissions = store.getters && store.getters.permissions
  let hasPermission = false;


  /**
   * 1.获取当前 用户的角色和权限
   * 2.角色包含admin，超级管理员，则强制放行
   * 3。如果角色不包含admin，则取判断权限，看是否包含权限，有则放行
   * 
   */


  if (roles.includes('admin')) {
    hasPermission = true
  } else {
    if (value && value instanceof Array) {
         
      if (value.length > 0) {
        let definePermission = value
       
        
        hasPermission =  definePermission.some(v => {
          return permissions.includes(v)
        })

       }
    } else {
      throw new Error(`功能所需要的权限列表必须是一个数组`)
    }
  }

  if (!hasPermission) {
    el.parentNode && el.parentNode.removeChild(el)
  }
}

export default {
  inserted(el, binding) {
    checkPermission(el, binding)
  },
  update(el, binding) {
    checkPermission(el, binding)
  }
}
